import axios from "axios";

class API {
  constructor({ url, method }) {
    this.url = url;
    this.method = method;
  }
}

function replaceVaribles (url, variables) {
  if (!variables) {
    return url;
  }

  if (process.env.NODE_ENV === "development") {
    console.log("Replace variables: ", variables);
  }

  for (let [name, value] of Object.entries(variables)) {
    url = url.replace("${" + name + "}", value);
  }
  return url;
}

function handleFulfill ({ module, url, method, data, params, variables }) {
  url = module + replaceVaribles(url, variables);

  if (process.env.NODE_ENV === "development") {
    const context = {
      module,
      url,
      method,
      data,
      params,
      variables
    }
    console.log("Handle fulfill: ", JSON.stringify(context));
  }
  return axios(url, {
    method,
    params,
    data
  });
}

function createFulfill (module) {
  // console.log("Create fulfill: ", module);
  return (API, { data, params, variables } = {}) =>
    handleFulfill({ module, ...API, data, params, variables });
}

function createApis (module, APIS) {
  const fulfill = createFulfill(module);
  const apis = {};
  for (let [name, API] of Object.entries(APIS)) {
    apis[name] = (args) => fulfill(API, args);
  }
  return apis;
}

export { API, createFulfill, createApis };
